package main

import (
	"flag"
	"fmt"
	"github.com/Desserts/notifier"
	log "github.com/Sirupsen/logrus"
	simpleJson "github.com/bitly/go-simplejson"
	"hj-check-in/tool"
	"io/ioutil"
	"net/http"
	"os"
)

var (
	flagt   string
	flaguid int64
	email   notifier.EmailNotifier
	logPath = "/home/Laily/go/src/hj-check-in/hj-checkin.log"
)

type Record struct {
	name string
	info map[string]string
}

func init() {
	flag.StringVar(&flagt, "t", "", "what type you want")
	flag.Int64Var(&flaguid, "id", 0, "userid")
	flag.Parse()
	email = notifier.NewEmailNotifier("smtp.exmail.qq.com:25", "service@laily.me", "Service123")
	initLogFile()
}

func initLogFile() {
	file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY, 0666)
	if err == nil {
		log.SetOutput(file)
	} else {
		log.Info("Failed to log to file, using default stderr")
	}
}

func Do() {
	record := make(map[string][]string, 0)
	res := tool.GetTasks()
	cookies := make(map[string]string, 0)
	for _, v := range res {
		username := string(v["name"])
		fmt.Printf("%s checking in %s...\n", string(v["name"]), string(v["stname"]))
		_, exist := cookies[username]
		if !exist {
			cookies[username] = Login(string(v["url"]))
		}
		resp := CheckIn(fmt.Sprintf(`{"leagueID":"%s"}`, string(v["stid"])), cookies[string(v["name"])])
		info := ParseRes(username, string(v["stname"]), resp)
		if info != "" {
			// 签到成功则不记录
			record[string(v["email"])] = append(record[string(v["email"])], info)
		}
	}
	Notice(record)
}

func Login(url string) string {
	header := &map[string]string{}
	resp := tool.Http("GET", url, "", header)
	cookieStr := ""
	for _, v := range resp.Cookies() {
		cookieStr += fmt.Sprintf("%s=%s;", v.Name, v.Value)
	}
	return cookieStr
}

func CheckIn(param, cookie string) *http.Response {
	url := "https://st.hujiang.com/ajax/pluginPostAjax.asmx/AddCheckIn"
	params := param
	header := &map[string]string{
		"Cookie":       cookie,
		"Content-Type": "application/json",
	}
	resp := tool.Http("POST", url, params, header)
	return resp
}

func ParseRes(username string, stname string, resp *http.Response) string {
	str, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read body wrong: ", err)
	}
	jsondata, err := simpleJson.NewJson(str)
	if err != nil {
		fmt.Println("get Response json wrong: ", err)
		fmt.Println("the resp str: ", string(str))
		return fmt.Sprintf("%s: [%s] 签到失败，沪江抽了", username, stname)
	}
	ok, err := jsondata.Get("d").Get("saveOK").Int()
	switch ok {
	case -2:
		//return fmt.Sprintf("%s: [%s] 今天已经签到了", username, stname)
		return ""
	case 0:
		//return fmt.Sprintf("%s: [%s] 签到成功", username, stname)
		return ""
	default:
		return fmt.Sprintf("%s: [%s] 签到应该失败了，不知道啥情况 %d", username, stname, ok)
	}
}

func Notice(record map[string][]string) {
	for k, v := range record {
		content := ""
		for _, vv := range v {
			content = content + vv + "<br/>"
		}
		email.SendMail(k, "沪江签到", content)
	}
}

func Test() {
	url := "http://pass.hujiang.com/Handler/UCenter?action=Login&callback=jQuery18306946046963326837_1479658153850&userName=yzhl314%40126.com&password=8fef625c4d5f11139e5755e82a123608&imgcode=&token=4e8ef473e7064a89babde5043cc0697e&_=1479658179211"
	cookie := Login(url)
	param := `{"leagueID":"879"}`
	CheckIn(param, cookie)
}

func main() {
	if flagt == "addtask" {
		log.Println("doing add task")
		if flaguid > 0 {
			tool.GetAllST(flaguid)
		} else {
			log.Println("input uid error")
		}
	} else if flagt == "run" {
		log.Println("doing check in")
		Do()
	} else if flagt == "special" {
		tool.AddBatchUser()
	} else {
		log.Println("please input type")
		flag.Usage()
	}

	// Test()
	// CheckIn()

}
